<template>
	<view class="page">
		<cu-custom bgColor="bg-white"  :isBack="true"><block slot="content">我的订单</block></cu-custom>
		<view class="bg-white margin-bottom shadow" style="z-index: 1999;position: fixed;width: 100%;">
			<!-- <view class="cu-bar search bg-white">
				<view class="search-form round">
					<text class="cuIcon-search"></text>
					<input @focus="inputFocus" :value="keyword"  @input="inputChange" @confirm="onKeywordConfirm" :adjust-position="false" type="text" placeholder="搜索我的订单" confirm-type="search"></input>
				</view>
			</view>	 -->
			<view class="bg-white nav overHidden" style="height:100rpx;width: 100%; padding: 0 10rpx;">
				<view class="flex justify-around align-center">
					<view class="cu-item":class="index===active?'text-theme cur':''"v-for="(item, index) in menuList" :key="index" @tap="CheckType(index)" :data-id="index" style="margin: 0;">
						<view>{{item.title}}</view>
						<text class='cu-tag badge' v-if="orderStatus[item.tag]>0 && index<5">{{orderStatus[item.tag]}}</text>
						<text class='cu-tag badge1' v-if="orderStatus[item.tag]>0&& index==5">{{orderStatus[item.tag]}}</text>
					</view>
				</view>	
			</view> 
		</view>
		<mescroll-uni ref="mescrollRef" @init="mescrollInit" height="90%" top="120" :down="downOption" @down="downCallback" :up="upOption" @up="upCallback" @emptyclick="emptyClick">
			<view class="margin-top-sm" v-for="(seller, index) in orderList" :key="index">
				<view class="cu-list menu card-menu margin-top-sm margin-left-sm margin-right-sm padding-bottom overHidden">
					<view class="cu-item">
						<view class="content flex align-center justify-between">
							<view class="flex align-center">
								<text class="cuIcon-shop text-theme" style="font-size: 18px;"></text>
								<text class="text-black text-bold text-df margin-left-sm title_line_1" style="flex:1; line-height: 32rpx;max-width: 400rpx;">{{seller.seller_name}}</text>
							</view>
							<view class="wq-order-text-orange text-sm">{{checkOrderStatus(seller)}}</view>
						</view>
					</view>
					<view class="cu-item padding overHidden padding-top-sm radius-lr-20" style="align-items: flex-start;flex-wrap: wrap;" v-for="(item,index1) in seller.sku_list" :key="index1"
						:style="index1!=0?'padding-top: 20rpx;':''">
						<view class="cu-avatar radius goodsImg" :style="'background-image:url('+item.goods_image+');'" @tap="goOrderDetail(seller.sn)"></view>
						<view class="content flex-direction margin-left" style="align-items: flex-start;flex-wrap:wrap;width: 100%;height: 180rpx;" @tap="goOrderDetail(seller.sn)">
							<view class="flex-column justify-start" style="width:100%;">
								<view class="flex algin-start" style="width:100%;">
									<view style="flex:1;">
										<view class="text-df" style="line-height: 32upx;font-weight: 400;">{{item.name}}</view>
									</view>
									<view class="singlePrice" style="line-height: 32upx;">
										<text class="text-gray text-sm">￥{{item.goods_type==='INDUCTION'?item.cost:izmember?item.cost:item.subtotal | formatPrice}}</text>
										<text class="text-gray text-sm" style="text-align: right;">x{{item.num}}</text>
									</view>
								</view>
							</view>
							<view class="text-999">
								<text style="font-size: 22upx;">
									规格：{{item | formatterSkuSpec}}
								</text>
							</view>
						</view>
						<view class="action text-sm flex justify-end align-center " style="width: 100%;vertical-align: bottom;" v-if="index1+1===seller.sku_list.length">
							<view class="text-999">共{{seller.sku_list.length}}件</view> 
							<view class="text-333 text-sm" style="margin-left: 6upx;">{{seller.order_status==='CONFIRM'?'需':'实'}}付款:</view>
							<view class="text-red text-lg text-bold">￥{{seller.order_amount |formatPrice}}</view>
						</view>
						<!-- <view class="flex margin-bottom margin-top-sm"  v-if="index1+1===seller.sku_list.length && seller.order_status==='CONFIRM'||seller.order_status==='SHIPPED'||seller.order_status==='COMPLETE'||seller.order_status==='ROG'|| seller.order_status=='PAID_OFF'|| seller.order_status=='AFTER_SERVICE'" style=" width:100% ;"> -->
						<view class="flex margin-bottom margin-top-sm"  v-if="index1+1===seller.sku_list.length" style=" width:100% ;">
							<view class="flex justify-end align-center" style="justify-content: flex-end;width: 100%;">
								<button class="cu-btn line-black text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='CONFIRM'" @tap="showModal(seller.sn)">取消订单</button>
								<!-- <button class="cu-btn line-black text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='CONFIRM'" @tap="editAddr(seller.sn)">修改地址</button> -->
								<button class="cu-btn line-pay text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='CONFIRM'" @tap="pay(seller.sn)">去付款</button>
								<button class="cu-btn line-black text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='COMPLETE' || seller.order_status=='PAID_OFF'" @tap="applyAfterSafe(seller,seller.sn)">取消订单</button>
								<!-- <button class="cu-btn line-black text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;"  @tap="applyAfterSafe(seller,seller.sn)">取消订单</button> -->
								<button class="cu-btn line-pay text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='SHIPPED'" @tap="getExpress(seller,seller.ship_no)">查看物流</button>
								<button class="cu-btn line-pay text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='SHIPPED'" @tap="confirmRog(seller.sn)">确认收货</button>
								<!-- <button class="cu-btn line-black text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='ROG'" @tap="askInvoice()">开具发票</button> -->
								<!-- <button class="cu-btn line-black text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='ROG'" @tap="applyAfterSafe(seller.sn)">申请售后</button> -->
								<button class="cu-btn line-pay text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" v-if="seller.order_status==='ROG'||seller.order_status==='COMPLETE'" @tap="comment(seller.sn,seller.sku_list)">评价</button>
								<!-- <button class="cu-btn line-pay text-333 text-sm margin-left-sm" style="width:160rpx;border-radius: 20rpx;" @tap="comment(seller.sn,seller.sku_list)">评价</button> -->
							</view>
						</view>
					</view>
				</view>
			</view>
		</mescroll-uni>
		<view class="cu-modal bottom-modal " :class="cancelshowModal?'show':''" style="z-index: 99999;">
			<view class="cu-dialog radius">
				<view class="cu-bar bg-white">
					<view class="action"></view>
					<view class="content text-df text-fw600">请选择取消原因</view>
					<view class="action text-333 cuIcon-close text-lg" style="font-size: 30rpx;" @tap="hideModal"></view>
				</view>
				<scroll-view scroll-y class="padding bg-white" style="text-align: left;height: 50vh; padding-bottom: 100rpx;">
					<view class="padding-top-sm" style="border-top: 1px solid #F5F5F5;border-bottom: 1px solid #F5F5F5;">
						<view class="text-fw600 text-333 text-lg">温馨提示</view>
						<view class="flex-direction text-333 text-lg padding-bottom-sm text-fw500">
							<view>1.限时特价，预约资格等购买优惠可能一并取消</view>
							<view>2.如遇到订单拆分，优惠券将换成同等价值京东返还</view>
							<view>3.支付券不予返还，支付优惠一并取消</view>
							<view>4.订单一旦取消，无法恢复</view>
						</view>
					</view>
					<view class="padding-top-xl" style="border-bottom: 1px solid #F5F5F5;">
						<view class="flex-direction text-333 margin-bottom-sm text-sm text-fw500">
							<view>请选择取消订单的原因(必选：)</view>
						</view>
					</view>
					<radio-group class="block margin-top" @change="RadioChange">
						<view class="cu-list sm-border ">
							<view class="cu-item" v-for="(item,index) in cancelReasonList" :key="index" @tap="handleCancel" :data-target="item.name">
								<label class="flex align-center flex-sub">
									<radio class="round" :class="checkActive===index?'checked':''" :checked="checkActive===index?true:false" style="height: 66rpx;"
									 :value="checkActive"></radio>
									<view class="flex-sub text-sm text-999 margin-left-sm" style="height: 50rpx;">{{item.name}}</view>
								</label>
							</view>
						</view>
					</radio-group>
				</scroll-view>
				<view class="flex">
					<view class="cu-btn bg-theme lg" style="position:fixed;bottom:0;width: 100%; border-radius: 0;" @tap="cancelOrder()">
						<text class="text-xl">提交</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import MescrollMoreItemMixin from "@/components/mescroll-uni/mixins/mescroll-more-item.js";
	import * as Order_API from '@/api/order.js'
	import * as Trade_API from '@/api/trade.js' 
	import * as Pay_API from '@/api/pay.js'
	import * as Foundation from '@/utils/Foundation.js'
	let client_type = 'MINI'
	export default {
		mixins: [MescrollMixin,MescrollMoreItemMixin], 
		data() {
			return {
				downOption:{
					auto:false // 不自动加载 (mixin已处理第一个tab触发downCallback)
				},
				upOption:{
					auto:false,
					noMoreSize: 8, //列表的总数量要大于半页才显示无更多数据;默认5
					empty:{
						icon:'/static/images/empty/empty_order.png',
						tip: '您还没有相关订单，快去下单吧'
					}
				},
				active:0,
				menuList:[
					{title:"全部",tag:''},
					{title:"未支付",tag:'wait_pay_num'},
					{title:"待发货",tag:'wait_ship_num'},
					{title:"待收货",tag:'wait_rog_num'},
					{title:"待评价",tag:'wait_comment_num'},
					{title:"售后",tag:'refund_num'},
				],
				orderList:[],
				params:{
					page_no:1,
					page_size:20,
					// order_status:'ALL',
					shop_id:uni.getStorageSync('shop').shop_id
				},
				count:0,
				isEdit:false,
				type:'',
				orderStatus:uni.getStorageSync('orderStatus')||{},
				izmember:uni.getStorageSync('role').id?true:false,
				finished:false,
				loadingText:'加载完毕',
				keyword: '',
				searchStatus: false,
				cancelshowModal:false,
				cancelReason:'',
				checkActive:1,
				cancelReasonList:[
					{name:'订单不能按时送达'},
					{name:'操作有误(商品、地址选错)'},
					{name:'重复下单/误下单'},
					{name:'其他渠道价格更低'},
					{name:'该商品降价了'},
					{name:'不想买了'},
					{name:'商品无货'},
					{name:'其他原因'}
				],
				selextedSN:'',
				loading:false,
				checkActive:0,
				izreturn:false
			}
		},
		watch:{
			active(newVal) {
				this.active = newVal
				if(this.active=== 1){
					this.params.order_status = 'WAIT_PAY'
				} else if(this.active=== 2){
					this.params.order_status = 'WAIT_SHIP'
				} else if(this.active=== 3){
					this.params.order_status = 'WAIT_ROG'
				}else if(this.active=== 4){
					this.params.order_status = 'WAIT_COMMENT'
				}else if(this.active=== 5){
					this.params.order_status = 'REFUND'
				}else if(this.active=== 0){
					this.params.order_status = 'ALL'
				}
				this.loading =false
				this.izreturn = true
			},
			type(newVal) {
				this.type = parseInt(newVal)
				this.active = parseInt(newVal)
			}
		},
		onLoad(e) {
			// if(e.type){
			// 	this.active = parseInt(e.type),
			// 	this.type = parseInt(e.type)
			// }
			if(e.type){
				this.active = parseInt(e.type)
			}
			this.izreturn = true
		},
		onShow() {
			
			const pages = getCurrentPages()
			const currPage = pages[pages.length - 1]  // 当前页
			console.log(currPage)
			if(currPage.data.refresh){
				currPage.data.refresh=0
				
			}
			// this.upCallback()
		},
		
		methods:{
			/*下拉刷新的回调 */
			downCallback() {
				// this.params.keyword = ''
				this.params.page_no =1
				this.mescroll.resetUpScroll()
			},
			upCallback(page) {
				if(!this.loading){
					setTimeout(()=>{
						Order_API.getOrderList(this.params).then(res =>{
							this.searchStatus = true
							this.mescroll.endSuccess(res.data.length)
							if(this.params.page_no ==1) this.orderList = []
							this.orderList = this.orderList.concat(res.data)
							this.params.page_no+=1
							this.getOrderStatusNum()
						}).catch(()=>{
							this.mescroll.endErr();
						})
					},300)
				}
			},
			//点击空布局按钮的回调
			emptyClick(){
				uni.showToast({
					title:'点击了按钮,具体逻辑自行实现'
				})
			},
			getOrderStatusNum(){
				let shop_id = uni.getStorageSync('shop').shop_id
				Order_API.getOrderStatusNum(shop_id).then(res =>{
					this.orderStatus = res
					uni.setStorageSync('orderStatus',res)
				})
			},
			inputChange(e) {
			    this.keyword = e.detail.value.replace(/\s+/g,"")
				if(this.keyword.replace(/\s+/g,"")){
					this.searchStatus = false
				}else{
					this.searchStatus = true
				}
			},   
			inputFocus(e) {
			    this.searchStatus = false
			},
			onKeywordConfirm(event) {
				let keyword = event.detail.value.replace(/\s+/g,"")
				if(!keyword &&  keyword=== ''){
					uni.showToast({
						title:'请输入关键词进行搜索',
						icon:'none'
					})
					this.searchStatus = false
				}else{
					this.searchStatus = true
					this.params.keyword = event.detail.value
					this.params.page_no =1
					setTimeout(()=>{
						Order_API.getOrderList(this.params).then(res =>{
							this.searchStatus = true
							this.mescroll.endSuccess(res.data.length)
							if(this.params.page_no ==1) this.ranklist = []
							this.ranklist = this.ranklist.concat(res.data)
							this.params.page_no+=1
							this.getOrderStatusNum()
						}).catch(()=>{
							this.mescroll.endErr();
						})
					},500)
				}
			},
			GET_OrderList(e){
				// this.CheckType(e)
				if (!this.finished){
					Order_API.getOrderList(this.params).then(res=>{
						if(res.data.length<1 || !res.data){
							this.finished = true
							this.loadingText = '到底了'
						}else{
							this.orderList = [...this.orderList,...res.data]
							this.loadingText = '查看更多'
						}
					}).catch(()=>{
						this.loadingText = '到底了'
					})
					
					this.getOrderStatusNum()
				}
			},
			CheckType(e){
				this.loading = true
				this.scrollLeft = (e - 1) * 60
				this.active = e
				// this.finished = false
				
				this.params.page_no = 1
				this.orderList = []
				this.loading = false
				// this.GET_OrderList()
				setTimeout(() =>{
					this.upCallback()
				},200)
			},
			goOrderDetail(sn){
				uni.navigateTo({
					url:'./orderDetail?sn='+sn+'&active='+this.active
				})
			},
			checkOrderType(params){
				switch(params.order_status){
					case 'CONFIRM':
					this.izcancelOrder = true
					this.izNeddPay = true
					return this.pay(params)
					case 'PAID_OFF':
					this.izcancelOrder = true
					return "提醒卖家发货"
					case 'SHIPPED':
					this.izconfirmRog = true
					return this.confirmRog(params)
					case 'ROG':
					this.izdelOrder = true
					case 'COMPLETE':
					return "去评价"
					case 'CANCELLED':
					this.izdelOrder = true
					return "取消订单"
					case 'AFTER_SERVICE':
					return "查看售后"
				}
			},
			checkOrderStatus(order){
				switch(order.order_status){
					case 'CONFIRM':
					return "等待买家付款"
					case 'PAID_OFF':
					return "等待卖家发货"
					case 'SHIPPED':
					return "卖家已发货"
					case 'ROG':
					return "买家已收货"
					case 'COMPLETE':
					return '已完成'
					case 'CANCELLED':
					return '订单已取消'
					case 'AFTER_SERVICE':
					return "售后处理中"
					default:
					return ""
				}
			},
			pay(sn){
				let params = {
					payment_plugin_id:'weixinPayPlugin',
					pay_mode:'normal',
					client_type:client_type
				}
				// let trade_type = this.trade_type==='cart'? 'order':'trade'
				let trade_type = 'order'
				Pay_API.Pay(trade_type,sn,params).then(res =>{
					let nonceStr=res.res.nonceStr
					let	timeStamp=res.res.timeStamp
					let	_package=res.res.package
					let	paySign=res.res.paySign
					let signType=res.res.signType
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: timeStamp,
						nonceStr:nonceStr,
						package: _package,
						signType: signType,
						paySign: paySign,
						success: res=> {
							console.log('支付返回',res)
							uni.showToast({
								title: "支付成功",
								duration: 2000,
								icon: 'none'
							});
							this.clearPaymentOrder()
							uni.navigateBack({
								delta: -1
							})
						},
						fail: err=> {
							console.log('支付报错',err)
							if(err.errMsg === 'requestPayment:fail cancel'){
								uni.showToast({
									title: "已取消支付",
									icon: 'none'
								});
							}else{
								uni.showModal({
									content: "支付失败,原因为:\n " + err.errMsg,
									showCancel: false,
								})
							}
						}
					})
				})
			},
			editAddr(sn){
				uni.navigateTo({
					url:'/pages/profile/address/addrList?izOrder=1'
				})
			},
			getExpress(order,ship_no){
				consolel.log(order)
				uni.navigateTo({
					url:'./logistics?ship_no='+ship_no
				})
			},
			confirmRog(sn){
				uni.showModal({
					title: '收货提示',
					content: '你确定已收到购买的商品?',
					success: (res)=>{
						if (res.confirm) {
							Order_API.confrimRog(sn).then(res=>{
								if(res === 'SUCCESS'){
									uni.showToast({
										icon:'success',
										title:'收货成功'
									})
								}else{
									uni.showToast({
										icon:'none',
										title:'确认收货失败'
									})
								}
								this.CheckType(this.active)
							})
						} 
					}
				})
			},
			delOrder(){
				uni.showModal({
					title: '删除提示',
					content: '你确定要删除该订单吗?',
					success: (res)=>{
						if (res.confirm) {
							Order_API.deleteOrder(this.sn).then(res =>{
								uni.showToast({
									icon:'success',
									title:'删除成功'
								})
								// console.log(this.active)
								this.CheckType(this.active)
							})
						}
					}
				})
			},
			showModal(sn){
				this.selextedSN = sn
				this.cancelshowModal = true
			},
			hideModal(){
				this.cancelshowModal = false
			},
			handleCancel(e){
				this.cancelReason =  e.currentTarget.dataset.target
			},
			RadioChange(e) {
				this.radio = e.detail.value
			},
			// 取消订单
			cancelOrder(sn){
				if(!this.cancelReason){
					this.cancelReason = this.cancelReasonList[0].name
				}
				if(this.selextedSN!=''){
					Order_API.cancelOrder(this.selextedSN,this.cancelReason).then(res =>{
						// this.CheckType(this.active)
						uni.showToast({
							title:'取消成功',
							icon:'success'
						})
						this.hideModal()
						this.CheckType(this.active)
					})
				}
			},
			comment(sn,sku_list){
				let sku_id = ''
				if(sku_list){
					sku_list.map(item =>{
						sku_id = item.sku_id
					})
				}
				uni.setStorage({
					key:'orderCommentSuk',
					data:sku_list,
					success() {
						uni.navigateTo({
							url:'./orderComment?sn='+sn
						})
					}
				})
				
			},
			applyAfterSafe(order,sn){
				if(order.sku_list){
					uni.setStorageSync('goods_applyAfter',order.sku_list)
					setTimeout(()=>{
						uni.navigateTo({
							url:'./afterSafeService?sn='+sn
						})
					},500)
				}
			},
		}
	}
</script>

<style lang="scss">
.fixed{
	position: fixed;
	z-index: 19999;
	top:0
}	
.list{
  height: 93vh;
}
.list .item{
  display: flex;
  border-bottom: 1px solid #EDEDED;
  padding: 0 16px;
  height: 95px;
  align-items: center;
}
.loading-text {
	width: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 60upx;
	color: #979797;
	font-size: 24upx;	
}
.list .label{
  flex: 0 0 auto;
  padding:10px 0;
}
.list .content{
  flex-grow: 1;
  display:flex;
}
.list .content image{
  flex: 0 0 auto;
  height: 76px;
  width: 76px;
  padding-right:10px;
}
.list .content .text{
  flex-grow: 1;
  font-size: 14px;
}
.list .content .title{
  overflow: hidden;
}
.list .content .spec{
  font-size: 12px;
  color: #333333;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-height: 24px;    
  max-height: 24px;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.list .content .price{
  display: flex;
  font-size: 16px;
}
.list .content .price text:nth-child(1){
  color: #ff5f19;
  flex: 1 0 50%;
}
.list .content .price text:nth-child(2){
  color: #999999;
  flex: 1 0 50%;
  text-align: right;
}
/deep/.cu-list.menu>.cu-item:after {
		border-bottom: none;
		height: 60upx;
	}
	/deep/.cu-list.menu>.cu-item  {
	min-height: 80rpx;
	}
	/deep/.cu-list.menu>.cu-item .content>text[class*=cuIcon] {
		width: 18px;
		text-align: left;
	}

.empty{
	  width: 100%;
	  height: 85vh;
	  display: flex;
	  justify-content: center;
	  align-cartList: center;
	  color: #666;
	  font-size: 28upx;
	  padding-bottom: 80upx;
}
/deep/.cu-tag.badge {
	border-radius: 200rpx;
	position: relative;
	top: -116rpx;
	right: 10px;
	font-size: 20rpx;
	padding: 0rpx 10rpx;
	height: 28rpx;
	color: #ffffff;
	left: 70rpx;
}
.badge1 {
	background-color: #dd514c !important;
	border-radius: 200rpx;
	position: relative;
	top: -116rpx;
	right: 10px;
	font-size: 20rpx;
	padding: 0rpx 10rpx;
	height: 28rpx;
	color: #ffffff;
	left: 50rpx;
}
.singlePrice{
	display: flex;
	flex-direction: column;
	margin-left: 10rpx;
}
/deep/.cu-btn {
	height: 50rpx;
	border-radius: 14rpx;
}
/deep/.cu-btn[class*="line"]::after{
	border: 1px solid #333;
	border-radius: 30rpx;
}
/deep/radio::before,checkbox::before {
margin-top: -14px;
}
.radius-lr-20{
	overflow:hidden;
	border-bottom-left-radius: 20rpx;
	border-bottom-right-radius: 20rpx;
}
</style>
